// cloudfunctions/updateUserInfo/index.js
const cloud = require('wx-server-sdk')

cloud.init({
  env: 'cloud1-3gew2xhnadfbd1bd'
})

const db = cloud.database()

/**
 * 更新用户信息云函数
 * 功能：更新用户的昵称、头像等信息
 */
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  const openId = wxContext.OPENID
  
  try {
    const updateData = {
      updateTime: new Date()
    }
    
    // 只更新传入的字段
    if (event.nickName !== undefined) {
      // 验证昵称长度
      if (event.nickName.length > 20) {
        return {
          success: false,
          error: '昵称不能超过20个字符'
        }
      }
      updateData.nickName = event.nickName
    }
    
    if (event.avatarUrl !== undefined) {
      updateData.avatarUrl = event.avatarUrl
    }
    
    if (event.gender !== undefined) {
      updateData.gender = event.gender
    }
    
    const result = await db.collection('users').where({
      _openid: openId
    }).update({
      data: updateData
    })
    
    if (result.stats.updated === 0) {
      return {
        success: false,
        error: '用户不存在'
      }
    }
    
    return {
      success: true,
      message: '更新成功'
    }
  } catch (err) {
    console.error('更新用户信息失败:', err)
    return {
      success: false,
      error: err.message
    }
  }
}
